<template>
  <div class="app-container">
    <!-- 房价趋势走线图一搜索框 -->
    <div class="filter-container">
      <h3>房价趋势走线图一</h3>
      <el-form :model="queryParams1" ref="queryForm1" size="small" :inline="true" label-width="68px">
        <el-form-item label="区域名称" prop="areaName">
          <el-select v-model="queryParams1.areaName" placeholder="请选择区域" clearable>
            <el-option
              v-for="area in areaOptions"
              :key="area"
              :label="area"
              :value="area"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleHistoryQuery1">查询历史数据</el-button>
        </el-form-item>
      </el-form>
      <el-form :model="queryParams1" ref="queryForm1" size="small" :inline="true" label-width="68px" style="margin-top: 10px;">
        <el-form-item label="最终月份" prop="endQuarter">
          <el-input
            v-model="queryParams1.endQuarter"
            placeholder="格式：YYYYQQ"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handlePredictQuery1" style="background-color: #67C23A; border-color: #67C23A;">预测未来数据</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery1">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 房价趋势走线图二搜索框 -->
    <div class="filter-container" style="margin-top: 20px;">
      <h3>房价趋势走线图二</h3>
      <el-form :model="queryParams2" ref="queryForm2" size="small" :inline="true" label-width="68px">
        <el-form-item label="区域名称" prop="areaName">
          <el-select v-model="queryParams2.areaName" placeholder="请选择区域" clearable>
            <el-option
              v-for="area in areaOptions"
              :key="area"
              :label="area"
              :value="area"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleHistoryQuery2">查询历史数据</el-button>
        </el-form-item>
      </el-form>
      <el-form :model="queryParams2" ref="queryForm2" size="small" :inline="true" label-width="68px" style="margin-top: 10px;">
        <el-form-item label="最终月份" prop="endQuarter">
          <el-input
            v-model="queryParams2.endQuarter"
            placeholder="格式：YYYYQQ"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handlePredictQuery2" style="background-color: #67C23A; border-color: #67C23A;">预测未来数据</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery2">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <div class="chart-container">
      <el-card class="chart-card">
        <div slot="header" class="chart-header">
          <span>房价趋势走线图一</span>
        </div>
        <div id="priceChart" class="chart"></div>
      </el-card>
    </div>

    <div class="chart-container">
      <el-card class="chart-card">
        <div slot="header" class="chart-header">
          <span>房价趋势走线图二</span>
        </div>
        <div id="compareChart" class="chart"></div>
      </el-card>
    </div>
  </div>
</template>

<script>
import { getPriceTrend, getAreaList } from "@/api/visualization/price_visualization"
import * as echarts from "echarts"

export default {
  name: "PriceVisualization",
  data() {
    return {
      loading: false,
      // 查询参数1（房价趋势走线图一）
      queryParams1: {
        areaName: undefined,
        endQuarter: undefined
      },
      // 查询参数2（房价趋势走线图二）
      queryParams2: {
        areaName: undefined,
        endQuarter: undefined
      },
      // 区域选项
      areaOptions: [],
      // 图表实例
      priceChart: null,
      compareChart: null,
      // 存储图表1的数据
      chart1HistoryData: [],
      chart1PredictData: [],
      // 存储图表2的数据
      chart2HistoryData: [],
      chart2PredictData: []
    }
  },
  mounted() {
    this.initCharts()
    this.loadAreaList()
  },
  beforeDestroy() {
    if (this.priceChart) {
      this.priceChart.dispose()
    }
    if (this.compareChart) {
      this.compareChart.dispose()
    }
  },
  methods: {
    /** 初始化图表 */
    initCharts() {
      // 价格趋势图表
      this.priceChart = echarts.init(document.getElementById('priceChart'))
      // 对比图表
      this.compareChart = echarts.init(document.getElementById('compareChart'))
      
      // 设置默认空数据图表显示（同时初始化两个图表）
      this.setDefaultChartOptions()
      
      // 响应式调整
      window.addEventListener('resize', () => {
        this.priceChart && this.priceChart.resize()
        this.compareChart && this.compareChart.resize()
      })
    },

    /** 加载区域列表 */
    loadAreaList() {
      getAreaList().then(response => {
        this.areaOptions = response.data
        // 移除默认加载数据，仅当用户点击查询时才加载
      })
    },



    /** 重置查询 - 房价趋势走线图一 */
    resetQuery1() {
      this.resetForm("queryForm1")
      // 清空存储的数据
      this.chart1HistoryData = []
      this.chart1PredictData = []
      // 重置后只显示走线图一的空默认图表
      this.setDefaultChartOptions('price')
    },
    
    /** 查询历史房价数据 */
    handleHistoryQuery1() {
      // 验证区域名称是否已选择
      if (!this.queryParams1.areaName) {
        this.$message.error('请选择区域名称！')
        return
      }
      
      this.loading = true
      // 使用现有的trend接口，只传入areaName参数获取数据
      const params = {
        areaName: this.queryParams1.areaName,
        startQuarter: '',
        endQuarter: ''
      }
      getPriceTrend(params).then(response => {
        this.loading = false
        let data = response.data
        // 检查是否有数据返回
        if (!data || data.length === 0) {
          this.$message.error('季度数据不存在或者输入格式有误！')
          return
        }
        // 只保留历史数据（priceType=1）
        const historyData = data.filter(item => item.priceType === 1)
        if (historyData.length === 0) {
          this.$message.error('没有找到该区域的历史房价数据！')
          return
        }
        // 更新历史数据存储
        this.chart1HistoryData = historyData
        // 合并数据并渲染图表
        this.renderCombinedPriceChart()
      }).catch(() => {
        this.loading = false
        this.$message.error('获取房价趋势走线图一数据失败')
      })
    },
    
    /** 预测未来数据 */
    handlePredictQuery1() {
      // 验证区域名称是否已选择
      if (!this.queryParams1.areaName) {
        this.$message.error('请选择区域名称！')
        return
      }
      
      // 验证最终季度是否已输入
      if (!this.queryParams1.endQuarter) {
        this.$message.error('请输入最终季度！')
        return
      }
      
      // 验证季度格式
      if (!this.validateQuarterInput(this.queryParams1.endQuarter)) {
        this.$message.error('季度数据不存在或者输入格式有误！')
        return
      }
      
      this.loading = true
      // 使用现有的trend接口，传入areaName和endQuarter参数（endQuarter为月份格式YYYYMM）（endQuarter为月份格式YYYYMM）
      const params = {
        areaName: this.queryParams1.areaName,
        startQuarter: '',
        endQuarter: this.queryParams1.endQuarter
      }
      getPriceTrend(params).then(response => {
        this.loading = false
        let data = response.data
        // 检查是否有数据返回
        if (!data || data.length === 0) {
          this.$message.error('季度数据不存在或者输入格式有误！')
          return
        }
        // 只保留预测数据（priceType=2或3）且季度不超过最终季度
        const predictData = data.filter(item => {
          return (item.priceType === 2 || item.priceType === 3) && item.quarter <= this.queryParams1.endQuarter
        })
        
        // 检查是否有预测数据
        if (predictData.length === 0) {
          this.$message.error('没有找到该区域的预测房价数据！')
          return
        }
        // 更新预测数据存储
        this.chart1PredictData = predictData
        // 合并数据并渲染图表
        this.renderCombinedPriceChart()
      }).catch(() => {
        this.loading = false
        this.$message.error('获取房价趋势走线图一数据失败')
      })
    },
    
    /** 合并渲染价格趋势图表 */
    renderCombinedPriceChart() {
      // 合并历史数据和预测数据
      const combinedData = [...this.chart1HistoryData, ...this.chart1PredictData]
      if (combinedData.length === 0) {
        this.setDefaultChartOptions()
        return
      }
      this.renderPriceChart(combinedData)
    },



    /** 重置查询 - 房价趋势走线图二 */
    resetQuery2() {
      this.resetForm("queryForm2")
      // 清空存储的数据
      this.chart2HistoryData = []
      this.chart2PredictData = []
      // 重置后只显示走线图二的空默认图表
      this.setDefaultChartOptions('compare')
    },
    
    /** 查询历史房价数据 */
    handleHistoryQuery2() {
      // 验证区域名称是否已选择
      if (!this.queryParams2.areaName) {
        this.$message.error('请选择区域名称！')
        return
      }
      
      this.loading = true
      // 使用现有的trend接口，只传入areaName参数获取数据
      const params = {
        areaName: this.queryParams2.areaName,
        startQuarter: '',
        endQuarter: ''
      }
      getPriceTrend(params).then(response => {
        this.loading = false
        let data = response.data
        // 检查是否有数据返回
        if (!data || data.length === 0) {
          this.$message.error('季度数据不存在或者输入格式有误！')
          return
        }
        // 只保留历史数据（priceType=1）
        const historyData = data.filter(item => item.priceType === 1)
        if (historyData.length === 0) {
          this.$message.error('没有找到该区域的历史房价数据！')
          return
        }
        // 更新历史数据存储
        this.chart2HistoryData = historyData
        // 合并数据并渲染图表
        this.renderCombinedCompareChart()
      }).catch(() => {
        this.loading = false
        this.$message.error('获取房价趋势走线图二数据失败')
      })
    },
    
    /** 预测未来数据 */
    handlePredictQuery2() {
      // 验证区域名称是否已选择
      if (!this.queryParams2.areaName) {
        this.$message.error('请选择区域名称！')
        return
      }
      
      // 验证最终季度是否已输入
      if (!this.queryParams2.endQuarter) {
        this.$message.error('请输入最终季度！')
        return
      }
      
      // 验证季度格式
      if (!this.validateQuarterInput(this.queryParams2.endQuarter)) {
        this.$message.error('季度数据不存在或者输入格式有误！')
        return
      }
      
      this.loading = true
      // 使用现有的trend接口，传入areaName和endQuarter参数
      const params = {
        areaName: this.queryParams2.areaName,
        startQuarter: '',
        endQuarter: this.queryParams2.endQuarter
      }
      getPriceTrend(params).then(response => {
        this.loading = false
        let data = response.data
        // 检查是否有数据返回
        if (!data || data.length === 0) {
          this.$message.error('季度数据不存在或者输入格式有误！')
          return
        }
        // 只保留预测数据（priceType=2或3）且季度不超过最终季度
        const predictData = data.filter(item => {
          return (item.priceType === 2 || item.priceType === 3) && item.quarter <= this.queryParams2.endQuarter
        })
        
        // 检查是否有预测数据
        if (predictData.length === 0) {
          this.$message.error('没有找到该区域的预测房价数据！')
          return
        }
        // 更新预测数据存储
        this.chart2PredictData = predictData
        // 合并数据并渲染图表
        this.renderCombinedCompareChart()
      }).catch(() => {
        this.loading = false
        this.$message.error('获取房价趋势走线图二数据失败')
      })
    },
    
    /** 合并渲染对比图表 */
    renderCombinedCompareChart() {
      // 合并历史数据和预测数据
      const combinedData = [...this.chart2HistoryData, ...this.chart2PredictData]
      if (combinedData.length === 0) {
        this.setDefaultChartOptions()
        return
      }
      this.renderCompareChart(combinedData)
    },

    /** 设置默认空数据图表选项 */
    setDefaultChartOptions(chartType = null) {
      const defaultOption = {
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
              const quarter = params[0].name
              let result = `区域: 未知<br/>月份: ${quarter}<br/>`
              params.forEach(param => {
                if (param.value !== null && param.value !== undefined) {
                  let label = '房价'
                  if (param.seriesName === 'LSTM预测') label = 'LSTM预测房价'
                  else if (param.seriesName === '决策树预测') label = '决策树预测房价'
                  result += `${label}: ${param.value} 元/㎡<br/>`
                }
              })
              return result
            }
        },
        legend: {
          data: ['历史房价', 'LSTM预测', '决策树预测']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: []
        },
        yAxis: {
          type: 'value',
          name: '房价 (元/㎡)',
          min: 0,
          // 初始状态下不显示其他刻度，只显示0
          axisLabel: {
            formatter: function(value) {
              return value === 0 ? '0' : ''
            }
          }
        },
        series: [
          {
            name: '历史房价',
            type: 'line',
            smooth: true,
            data: [],
            itemStyle: {
              color: '#5470c6'
            }
          },
          {
            name: 'LSTM预测',
            type: 'line',
            smooth: true,
            data: [],
            itemStyle: {
              color: '#91cc75'
            },
            lineStyle: {
              type: 'dashed'
            }
          },
          {
            name: '决策树预测',
            type: 'line',
            smooth: true,
            data: [],
            itemStyle: {
              color: '#fac858'
            },
            lineStyle: {
              type: 'dashed'
            }
          }
        ]
      }
      
      // 根据chartType参数决定重置哪个图表
      if (chartType === 'price' || chartType === null) {
        this.priceChart.setOption(defaultOption)
      }
      if (chartType === 'compare' || chartType === null) {
        this.compareChart.setOption(defaultOption)
      }
    },

    /** 渲染价格趋势图表 */
    renderPriceChart(data) {
      if (!data || data.length === 0) {
        this.setDefaultChartOptions('price')
        return
      }
      
      // 分离历史数据、LSTM预测数据和决策树预测数据
      const historyData = data.filter(item => item.priceType === 1)
      const lstmData = data.filter(item => item.priceType === 2)
      const decisionTreeData = data.filter(item => item.priceType === 3)
      
      // 合并所有季度并排序
      const quarters = [...new Set([...historyData, ...lstmData, ...decisionTreeData].map(item => item.quarter))]
        .sort()
        .map(q => this.formatQuarter(q))
      
      // 创建映射，方便查找对应季度的房价和区域信息
      const historyMap = new Map(historyData.map(item => [item.quarter, item.avgPrice]))
      const lstmMap = new Map(lstmData.map(item => [item.quarter, item.avgPrice]))
      const decisionTreeMap = new Map(decisionTreeData.map(item => [item.quarter, item.avgPrice]))
      const areaMap = new Map([...historyData, ...lstmData, ...decisionTreeData].map(item => [item.quarter, item.areaName]))
      const originalQuarterMap = new Map(quarters.map((q, index) => [q, [...historyData, ...lstmData, ...decisionTreeData].sort()[index].quarter]))
      
      // 根据排序后的季度生成价格数组
      const historyPrices = quarters.map(q => {
        const originalQuarter = [...historyData, ...lstmData, ...decisionTreeData].sort().find(item => this.formatQuarter(item.quarter) === q)?.quarter
        return historyMap.get(originalQuarter) || null
      })
      const lstmPrices = quarters.map(q => {
        const originalQuarter = [...historyData, ...lstmData, ...decisionTreeData].sort().find(item => this.formatQuarter(item.quarter) === q)?.quarter
        return lstmMap.get(originalQuarter) || null
      })
      const decisionTreePrices = quarters.map(q => {
        const originalQuarter = [...historyData, ...lstmData, ...decisionTreeData].sort().find(item => this.formatQuarter(item.quarter) === q)?.quarter
        return decisionTreeMap.get(originalQuarter) || null
      })
      
      // 获取区域名称
      const areaName = data[0]?.areaName || '未知区域'
      
      // 计算自适应的y轴配置
      const yAxisOptions = this.calculateYAxisOptions(data)
      
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
              const quarter = params[0].name
              const area = areaName
              
              let result = `区域: ${area}<br/>月份: ${quarter}<br/>`
              params.forEach(param => {
                if (param.value !== null && param.value !== undefined) {
                  let label = '房价'
                  if (param.seriesName === 'LSTM预测') label = 'LSTM预测房价'
                  else if (param.seriesName === '决策树预测') label = '决策树预测房价'
                  result += `${label}: ${param.value} 元/㎡<br/>`
                }
              })
              return result
            }.bind(this),
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        legend: {
          data: ['历史房价', 'LSTM预测', '决策树预测']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: quarters,
          axisLabel: {
            // 确保ECharts不会自动过滤标签
            interval: 0,
            formatter: function(value) {
              // 只显示每年的1月标签
              const month = parseInt(value.match(/(\d{1,2})月/)[1]);
              return month === 1 ? value : '';
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '房价 (元/㎡)',
          min: yAxisOptions.min,
          max: yAxisOptions.max,
          interval: yAxisOptions.interval,
          axisLabel: {
            formatter: '{value}'
          },
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          }
        },
        series: [
          {
            name: '历史房价',
            type: 'line',
            smooth: true,
          data: historyPrices,
          symbol: 'circle',
          symbolSize: 8,
          showSymbol: true,
          connectNulls: false,
          // 确保所有数据点都显示，移除可能导致数据点过滤的配置
          emphasis: {
            scale: true
          },
            itemStyle: {
              color: '#5470c6'
            },
            lineStyle: {
              width: 2
            },
            emphasis: {
              focus: 'item',
              itemStyle: {
                borderWidth: 3,
                borderColor: '#fff',
                shadowBlur: 10,
                shadowColor: 'rgba(0, 0, 0, 0.3)'
              },
              symbolSize: 12
            }
          },
          {
            name: 'LSTM预测',
            type: 'line',
            smooth: true,
          data: lstmPrices,
          symbol: 'circle',
          symbolSize: 8,
          showSymbol: true,
          connectNulls: false,
          // 确保所有数据点都显示，移除可能导致数据点过滤的配置
          emphasis: {
            scale: true
          },
            itemStyle: {
              color: '#91cc75'
            },
            lineStyle: {
              width: 2,
              type: 'dashed'
            },
            emphasis: {
              focus: 'item',
              itemStyle: {
                borderWidth: 3,
                borderColor: '#fff',
                shadowBlur: 10,
                shadowColor: 'rgba(0, 0, 0, 0.3)'
              },
              symbolSize: 12
            }
          },
          {
            name: '决策树预测',
            type: 'line',
            smooth: true,
            data: decisionTreePrices,
            symbol: 'circle',
            symbolSize: 8,
            showSymbol: true,
            connectNulls: false,
            emphasis: {
              scale: true
            },
            itemStyle: {
              color: '#fac858'
            },
            lineStyle: {
              width: 2,
              type: 'dashed'
            },
            emphasis: {
              focus: 'item',
              itemStyle: {
                borderWidth: 3,
                borderColor: '#fff',
                shadowBlur: 10,
                shadowColor: 'rgba(0, 0, 0, 0.3)'
              },
              symbolSize: 12
            }
          }
        ]
      }
      
      this.priceChart.setOption(option)
    },

    /** 渲染对比图表 */
    renderCompareChart(data) {
      if (!data || data.length === 0) {
        this.setDefaultChartOptions('compare')
        return
      }
      
      // 分离历史数据、LSTM预测数据和决策树预测数据
      const historyData = data.filter(item => item.priceType === 1)
      const lstmData = data.filter(item => item.priceType === 2)
      const decisionTreeData = data.filter(item => item.priceType === 3)
      
      // 合并所有季度并排序
      const quarters = [...new Set([...historyData, ...lstmData, ...decisionTreeData].map(item => item.quarter))]
        .sort()
        .map(q => this.formatQuarter(q))
      
      // 创建映射，方便查找对应季度的房价和区域信息
      const historyMap = new Map(historyData.map(item => [item.quarter, item.avgPrice]))
      const lstmMap = new Map(lstmData.map(item => [item.quarter, item.avgPrice]))
      const decisionTreeMap = new Map(decisionTreeData.map(item => [item.quarter, item.avgPrice]))
      
      // 根据排序后的季度生成价格数组
      const historyPrices = quarters.map(q => {
        const originalQuarter = [...historyData, ...lstmData, ...decisionTreeData].sort().find(item => this.formatQuarter(item.quarter) === q)?.quarter
        return historyMap.get(originalQuarter) || null
      })
      const lstmPrices = quarters.map(q => {
        const originalQuarter = [...historyData, ...lstmData, ...decisionTreeData].sort().find(item => this.formatQuarter(item.quarter) === q)?.quarter
        return lstmMap.get(originalQuarter) || null
      })
      const decisionTreePrices = quarters.map(q => {
        const originalQuarter = [...historyData, ...lstmData, ...decisionTreeData].sort().find(item => this.formatQuarter(item.quarter) === q)?.quarter
        return decisionTreeMap.get(originalQuarter) || null
      })
      
      // 获取区域名称
      const areaName = data[0]?.areaName || '未知区域'
      
      // 计算自适应的y轴配置
      const yAxisOptions = this.calculateYAxisOptions(data)
      
      const option = {
        tooltip: {
          trigger: 'axis',
          formatter: function(params) {
              const quarter = params[0].name
              const area = areaName
              
              let result = `区域: ${area}<br/>月份: ${quarter}<br/>`
              params.forEach(param => {
                if (param.value !== null && param.value !== undefined) {
                  let label = '房价'
                  if (param.seriesName === 'LSTM预测') label = 'LSTM预测房价'
                  else if (param.seriesName === '决策树预测') label = '决策树预测房价'
                  result += `${label}: ${param.value} 元/㎡<br/>`
                }
              })
              return result
            },
          axisPointer: {
            type: 'cross',
            label: {
              backgroundColor: '#6a7985'
            }
          }
        },
        legend: {
          data: ['历史房价', 'LSTM预测', '决策树预测']
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: quarters,
          axisLabel: {
            // 确保ECharts不会自动过滤标签
            interval: 0,
            formatter: function(value) {
              // 只显示每年的1月标签
              const month = parseInt(value.match(/(\d{1,2})月/)[1]);
              return month === 1 ? value : '';
            }
          }
        },
        yAxis: {
          type: 'value',
          name: '房价 (元/㎡)',
          min: yAxisOptions.min,
          max: yAxisOptions.max,
          interval: yAxisOptions.interval,
          axisLabel: {
            formatter: '{value}'
          },
          splitLine: {
            lineStyle: {
              type: 'dashed'
            }
          }
        },
        series: [
          {
            name: '历史房价',
            type: 'line',
            smooth: true,
            data: historyPrices,
            symbol: 'circle',
            symbolSize: 8,
            showSymbol: true,
            connectNulls: false,
            itemStyle: {
              color: '#5470c6'
            },
            lineStyle: {
              width: 2
            },
            emphasis: {
              focus: 'item',
              itemStyle: {
                borderWidth: 3,
                borderColor: '#fff',
                shadowBlur: 10,
                shadowColor: 'rgba(0, 0, 0, 0.3)'
              },
              symbolSize: 12
            }
          },
          {
            name: 'LSTM预测',
            type: 'line',
            smooth: true,
            data: lstmPrices,
            symbol: 'circle',
            symbolSize: 8,
            showSymbol: true,
            connectNulls: false,
            emphasis: {
              scale: true
            },
            itemStyle: {
              color: '#91cc75'
            },
            lineStyle: {
              width: 2,
              type: 'dashed'
            },
            emphasis: {
              focus: 'item',
              itemStyle: {
                borderWidth: 3,
                borderColor: '#fff',
                shadowBlur: 10,
                shadowColor: 'rgba(0, 0, 0, 0.3)'
              },
              symbolSize: 12
            }
          },
          {
            name: '决策树预测',
            type: 'line',
            smooth: true,
            data: decisionTreePrices,
            symbol: 'circle',
            symbolSize: 8,
            showSymbol: true,
            connectNulls: false,
            emphasis: {
              scale: true
            },
            itemStyle: {
              color: '#fac858'
            },
            lineStyle: {
              width: 2,
              type: 'dashed'
            },
            emphasis: {
              focus: 'item',
              itemStyle: {
                borderWidth: 3,
                borderColor: '#fff',
                shadowBlur: 10,
                shadowColor: 'rgba(0, 0, 0, 0.3)'
              },
              symbolSize: 12
            }
          }
        ]
      }
      
      this.compareChart.setOption(option)
    },
    
    /** 计算自适应的y轴配置 */
    calculateYAxisOptions(data) {
      // 从数据中提取所有价格值
      const allPrices = [...data].map(item => item.avgPrice).filter(price => price != null && price !== undefined && !isNaN(price))
      
      if (allPrices.length === 0) {
        return {
          min: 0,
          axisLabel: {
            formatter: function(value) {
              return value === 0 ? '0' : ''
            }
          }
        }
      }
      
      // 找到最高和最低价格
      const minPrice = Math.min(...allPrices)
      const maxPrice = Math.max(...allPrices)
      
      // 计算价格范围
      const priceRange = maxPrice - minPrice
      
      // 计算间隔：价格范围的10%，并取整
      let interval = Math.round(priceRange * 0.1)
      
      // 确保间隔至少为100
      interval = Math.max(interval, 100)
      
      // 计算y轴最小值（最低价格减去5个单位）
      let min = Math.floor((minPrice - interval * 5) / interval) * interval
      // 确保最小值不小于0
      min = Math.max(min, 0)
      
      // 计算y轴最大值（最高价格加上5个单位）
      let max = Math.ceil((maxPrice + interval * 5) / interval) * interval
      
      return {
        min,
        max,
        interval
      }
    },
    
    /** 格式化季度显示 */
    formatQuarter(quarter) {
      // 处理月份格式，如202601显示为2026年1月
      if (!quarter || quarter.toString().length !== 6) {
        return quarter
      }
      const year = quarter.toString().substring(0, 4)
      const month = quarter.toString().substring(4, 6)
      return `${year}年${parseInt(month)}月`
    },
    
    /** 解析季度格式 */
    parseQuarter(formattedQuarter) {
      // 如果已经是6位数字格式，直接返回
      if (/^\d{6}$/.test(formattedQuarter)) {
        return formattedQuarter
      }
      // 尝试从"2026年1月"格式解析
      const yearMatch = formattedQuarter.match(/(\d{4})年/)
      const monthMatch = formattedQuarter.match(/(\d{1,2})月/)
      if (yearMatch && monthMatch) {
        const year = yearMatch[1]
        const month = monthMatch[1].padStart(2, '0')
        return year + month
      }
      return formattedQuarter
    },
    
    /** 验证季度输入格式 */
    validateQuarterInput(quarter) {
      // 检查是否为空
      if (!quarter) {
        return false
      }
      
      // 检查格式是否为6位数字
      const monthRegex = /^\d{6}$/
      if (!monthRegex.test(quarter)) {
        return false
      }
      
      // 检查年份是否在有效范围内
      const year = parseInt(quarter.substring(0, 4))
      const month = parseInt(quarter.substring(4, 6))
      
      // 假设有效年份范围是2018年到2030年
      const currentYear = new Date().getFullYear()
      if (year < 2018 || year > 2030) {
        return false
      }
      
      // 检查月份是否在1-12之间
      if (month < 1 || month > 12) {
        return false
      }
      
      return true
    }
  }
}
</script>

<style scoped>
.filter-container {
  background: #fff;
  padding: 10px 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.filter-container h3 {
  margin-top: 0;
  margin-bottom: 10px;
  font-size: 16px;
  color: #333;
}

.chart-container {
  margin-top: 20px;
}

.chart-card {
  height: 400px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chart {
  width: 100%;
  height: 350px;
}
</style>
